const mongoose = require('mongoose')
var bcrypt = require('bcryptjs')
//var salt = bcrypt.genSaltSync(10);
//var hash = bcrypt.hashSync("B4c0/\/", salt);
//const SALT_WORK_FACTOR = 10
mongoose.connect('mongodb://localhost:27017/element-vue', {
  useNewUrlParser: true,
  useFindAndModify: true,
  useCreateIndex: true,
  useUnifiedTopology: true
})
//用户模式
const UserSchema=new mongoose.Schema({
  username: {
    type: String,
    unique:true//唯一，重复不插入数据库
  },
  password: {
    type: String,
    set(val){
      return bcrypt.hashSync(val, 10)//加密存储
    }
    /* set(){
      return bcrypt.genSalt(salt,function(err,salt){
        bcrypt.hash("B4c0/\/", salt, function (err, hash) {
          // Store hash in your password DB.
          if (err) {
            return err
          }
          this.password = hash
          //next()
        })
      })
    } */
  }
})

//使用pre中间件在用户信息存储前进行密码加密
/* UserSchema.pre('save',next=>{
  let user=this
  //加密
  bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
    if (err) {
      return next(err)
    }
    bcrypt.hash(user.password,salt,(err,hash)=>{
      if (err) {
        return next(err)
      }
      user.password=hash
      next()
    })
  })
}) */
const User = mongoose.model('User', UserSchema)

module.exports = {User};